import { v4 as uuidv4 } from 'uuid'
import dayjs from 'dayjs'
import Api from '@/api/'
import to from '@/utils/awaitTo'
import OSS from 'ali-oss'


/**
 * @description 生成UUID用户名字
 * @param {String} fileSimpleName 文件名
 * */
export const useGenerateFileName = (fileSimpleName: string) => {
  // 生成UUID并去掉其中的'-'
  const uuid = uuidv4().replace(/-/g, '')

  // 获取文件名
  const newFileName = `${fileSimpleName}`

  // 构建日期路径：avatar/2019/02/26/文件名
  const datePath = dayjs(new Date().getTime()).format('YYYYMMDD')

  // 判断文件类型并设置路径前缀
  const voiceOrVideoPath = 'milin'

  // 拼接文件名
  return `${voiceOrVideoPath}/${datePath}/${uuid}${newFileName}`
}


/**
 * @description 阿里OSS
 * */
export const createOssClient = async () => {
  return new Promise(async (resolve, reject) => {
    const [error, data] = await to(Api.common.AliossKey({}))
    if (error) return reject(error)

    const { accessKeyId, accessKeySecret, SecurityToken, expiration } = data
    const client: OSS = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: accessKeyId,
      accessKeySecret: accessKeySecret,
      bucket: 'huatiku',
      stsToken: SecurityToken,
      secure: true // 启用 HTTPS
      // 注意：refreshSTSTokenInterval 通常用于自动刷新 STS Token，但 OSS SDK 可能不支持直接配置此选项
      // 如果你需要自动刷新 STS Token，你可能需要自己实现逻辑
    })
    return resolve(client)
  })
}


/**
 * @description 下载
 * @param {Blob,MediaSource} downfile 下载源
 * @param {String} name 下载名字
 */
export function download(downfile: Blob | MediaSource | string, name: string, isClick = false) {
  const tmpLink = document.createElement('a')
  const objectUrl = typeof (downfile) === 'string' ? downfile : URL.createObjectURL(downfile)
  tmpLink.href = objectUrl
  tmpLink.download = name
  document.body.appendChild(tmpLink)

  // 使用setTimeout来确保元素已经添加到DOM中
  tmpLink.click()
  document.body.removeChild(tmpLink)
  URL.revokeObjectURL(objectUrl)
}


/**
 * @description 事件撮
 * */

export function CountDown(time: string) {

  const t = {
    text: '',
    status: ''
  }

  // 创建一个 Day.js 对象来表示 2024-03-28 16:20:38
  const targetDate = dayjs(time)

  // 计算三天后的日期
  const futureDate = targetDate.add(3, 'day')

  // 获取当前日期和时间
  const now = dayjs()

  // 计算两个日期之间的差值（毫秒）
  const diffInMilliseconds = futureDate.diff(now)
  const diffInDays = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24))
  const diffInHours = Math.floor((diffInMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const diffInMinutes = Math.floor((diffInMilliseconds % (1000 * 60 * 60)) / (1000 * 60))
  // const diffInSeconds = Math.floor((diffInMilliseconds % (1000 * 60)) / 1000)

  if (diffInDays < 0 && diffInHours < 0 && diffInMinutes < 0) {
    t.text =`(超时)${diffInDays}天${diffInHours}时${diffInMinutes}分`
    t.status = 'pass'
  } else {
    t.text = `(剩)${diffInDays}天${diffInHours}时${diffInMinutes}分`
    t.status = 'ing'
  }
  return t
}

